package com.sr.maven.servlet.module;

import com.sr.maven.entity.Emp;
import com.sr.maven.exception.LoginFailException;
import com.sr.maven.service.EmpService;
import com.sr.maven.service.impl.EmpServiceImpl;
import com.sr.maven.servlet.base.ModelBaseServlet;
import com.sr.maven.util.ImperialCourtConst;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class AuthServlet  extends ModelBaseServlet {

    private EmpService empService = new EmpServiceImpl();

    protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        try {
            //1.先获取请求参数
            String loginAccount = req.getParameter("loginAccount");
            String loginPassword = req.getParameter("loginPassword");
            //2.调用EmpService 的方法，执行登录的逻辑
            Emp emp =  empService.getEmpByLoginAccount(loginAccount,loginPassword);
            //3. 通过requet获取HTTPSession
            HttpSession session = req.getSession();
            //4.将查询的Emp对象存入Session域
            session.setAttribute(ImperialCourtConst.LOGIN_EMP_ATTR_NAME,emp);
            //5.前往指定的页面视图
//            String templateName  = "temp";
//            processTemplate(templateName,req,resp);
            resp.sendRedirect(req.getContextPath()+"/work?method=showMemorialsDigestList");
        }catch (Exception e){
            e.printStackTrace();
            //判断此处是否是 登录失败异常
            if(e instanceof LoginFailException){

            //如果是登录失败异常跳转回登录页面
            //存入请求域
                req.setAttribute("message",e.getMessage());
            //处理视图：index
            processTemplate("index",req,resp);

            }else{
            //如果不是登录异常则封装为运行时异常继续抛出
                throw  new RuntimeException(e);
            }

        }

    }


    protected void logout(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.通过request 对象获取 HttpSession对象
        HttpSession session = req.getSession();

        //2.将HttpSession设置失效
        session.invalidate();

        //3.回到index页面
        processTemplate("index",req,resp);
    }
}
